<template>
  <basePages>
    <view class="device-list">
      <view class="header">
        <text class="title">我的设备</text>
        <view class="add-btn-wrapper" @click="navigateToAdd">
          <view class="add-btn">
            <uni-icons type="plus" size="24" color="#409EFF"></uni-icons>
          </view>
        </view>
      </view>

      <view class="device-grid">
        <view v-if="deviceList.length === 0" class="empty-state">
          <image src="/static/images/empty-device.png" mode="aspectFit" class="empty-image"></image>
          <text class="empty-text">暂无设备，点击右上角按钮添加</text>
        </view>

        <view v-else class="device-cards">
          <view 
            v-for="device in deviceList" 
            :key="device.id" 
            class="device-card"
            @click="navigateToDetail(device.sn)"
          >
            <view class="card-header">
              <view class="device-icon">
                <uni-icons :type="getDeviceIcon(device.deviceType)" size="32" color="#409EFF"></uni-icons>
              </view>
              <view class="device-status" :class="{ 'status-online': device.status === 'active' }">
                {{ device.status === 'active' ? '在线' : '离线' }}
              </view>
            </view>

            <view class="card-content">
              <text class="device-name">{{ device.metaData?.name || getDeviceTypeName(device.deviceType) }}</text>
              <text class="device-type">{{ getDeviceTypeName(device.deviceType) }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </basePages>
</template>

<script setup>
import { ref, onMounted ,watch } from 'vue';
import { useDeviceStore } from '../../../store/modules/useDeviceStore';
import { useUserStore } from '../../../store/modules/useUserStore';
import { useBindingStore } from '../../../store/modules/useBindingStore';

const deviceStore = useDeviceStore();
const userStore = useUserStore();
const bindingStore = useBindingStore();
const deviceList = ref([]);

watch(() => userStore.curUserId, async () => {
  await fetchDeviceList();
});
watch(()=>deviceStore.getDeviceList,()=>{
  deviceList.value = deviceStore.getDeviceList;
})

// 获取设备列表
const fetchDeviceList = async () => {
  try {
    const res = await deviceStore.fetchDeviceList();
    if (res && res.code === 200) {
      deviceList.value = res.data;
    } else {
      // 如果API调用失败，使用store中的默认数据
      deviceList.value = deviceStore.getDeviceList;
    }
  } catch (error) {
    // 如果发生错误，使用store中的默认数据
    deviceList.value = deviceStore.getDeviceList;
    uni.showToast({
      title: error.message || '获取设备列表失败',
      icon: 'none'
    });
  }
};

// 获取设备图标
const getDeviceIcon = (type) => {
  const iconMap = {
    wearable: 'watch',
    BPMonitor: 'heart',
    BGMeter: 'scale',
    spO2Monitor: 'heart',
    ECGMonitor: 'heart',
    BFPMonitor: 'scale',
    Thermometer: 'thermometer',
    other: 'device'
  };
  return iconMap[type] || 'device';
};

// 获取设备类型名称
const getDeviceTypeName = (type) => {
  const nameMap = {
    wearable: '智能手表',
    BPMonitor: '血压计',
    BGMeter: '血糖仪',
    spO2Monitor: '血氧仪',
    ECGMonitor: '心电图仪',
    BFPMonitor: '体脂秤',
    Thermometer: '体温计',
    other: '其他设备'
  };
  return nameMap[type] || '未知设备';
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return '暂无数据';
  const d = new Date(date);
  return `${d.getMonth() + 1}月${d.getDate()}日 ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
};

// 跳转到添加设备页面
const navigateToAdd = () => {
  uni.navigateTo({
    url: '/pages/shared/devices/deviceAdd'
  });
};

// 跳转到设备详情页面
const navigateToDetail = (deviceSN) => {
  
  uni.setStorageSync('currentDeviceSN', deviceSN);
  uni.navigateTo({
    url: '/pages/shared/devices/deviceDetail'
  });
};

onMounted(() => {
  const role_ = userStore.userData.role;
  if(role_ == 'older'){
    deviceStore.setDevUserId(userStore.userData.id);
  }else{
    deviceStore.setDevUserId(bindingStore.getCurBindingId);
  }
  console.log('deviceStore.devUserId:', deviceStore.getDevUserId);

  fetchDeviceList();
});
</script>

<style lang="scss" scoped>
.device-list {
  padding: 20rpx;
  min-height: 100vh;
  background-color: #f8fafc;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10rpx;
  margin-bottom: 30rpx;

  .title {
    font-size: 36rpx;
    font-weight: 500;
    color: #333;
  }

  .add-btn-wrapper {
     width: 80rpx;
     height: 80rpx;
     display: flex;
     align-items: center;
     justify-content: center;
  }

  .add-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #ecf5ff;
    border-radius: 50%;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
     transition: all 0.2s ease;

    &:active {
      transform: scale(0.9);
      opacity: 0.8;
    }
  }
}

.device-grid {
  padding: 0 10rpx;

  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 100rpx 0;

    .empty-image {
      width: 240rpx;
      height: 240rpx;
      margin-bottom: 20rpx;
    }

    .empty-text {
      font-size: 28rpx;
      color: #999;
    }
  }
}

.device-cards {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.device-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  transition: all 0.2s ease;

   &:active {
    transform: scale(0.98);
    opacity: 0.9;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
  }

  .device-icon {
    width: 80rpx;
    height: 80rpx;
    background: #ecf5ff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .device-status {
    font-size: 24rpx;
    color: #909399;
    padding: 4rpx 16rpx;
    border-radius: 20rpx;
    background: #f4f4f5;

    &.status-online {
      color: #67c23a;
      background: #f0f9eb;
    }
  }

  .card-content {
      flex-grow: 1;
      display: flex;
      flex-direction: column;
      justify-content: flex-end;

    .device-name {
      font-size: 28rpx;
      font-weight: 500;
      color: #333;
      margin-bottom: 8rpx;
    }

    .device-type {
      font-size: 24rpx;
      color: #666;
    }
  }
}
</style>